<template>
  <div class="venue-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>场馆管理</h1>
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新增场馆
      </el-button>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards" v-if="stats">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ stats.total }}</div>
          <div class="stat-label">总场馆数</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number active">{{ stats.active }}</div>
          <div class="stat-label">活跃场馆</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number inactive">{{ stats.inactive }}</div>
          <div class="stat-label">停用场馆</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number maintenance">{{ stats.maintenance }}</div>
          <div class="stat-label">维护中</div>
        </div>
      </el-card>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="queryParams" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="queryParams.keyword"
            placeholder="搜索场馆名称、描述、地址"
            clearable
            @keyup.enter="handleSearch"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="选择状态" clearable style="width: 120px">
            <el-option label="活跃" value="ACTIVE" />
            <el-option label="停用" value="INACTIVE" />
            <el-option label="维护中" value="MAINTENANCE" />
          </el-select>
        </el-form-item>
        <el-form-item label="城市">
          <el-input
            v-model="queryParams.city"
            placeholder="输入城市"
            clearable
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item label="国家">
          <el-input
            v-model="queryParams.country"
            placeholder="输入国家"
            clearable
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-select
            v-model="queryParams.sortBy"
            placeholder="选择排序字段"
            style="width: 120px"
            @change="handleSortChange"
          >
            <el-option label="按排序值" value="sortOrder" />
            <el-option label="按名称" value="name" />
            <el-option label="按城市" value="city" />
            <el-option label="按创建时间" value="createdAt" />
          </el-select>
          <el-select
            v-model="queryParams.sortOrder"
            placeholder="排序方向"
            style="width: 80px; margin-left: 8px"
            @change="handleSortChange"
          >
            <el-option label="升序" value="asc" />
            <el-option label="降序" value="desc" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button
        type="danger"
        :disabled="selectedIds.length === 0"
        @click="handleBatchDelete"
      >
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
      <el-button
        type="warning"
        :disabled="selectedIds.length === 0"
        @click="handleBatchStatus('INACTIVE')"
      >
        批量停用
      </el-button>
      <el-button
        type="success"
        :disabled="selectedIds.length === 0"
        @click="handleBatchStatus('ACTIVE')"
      >
        批量启用
      </el-button>
    </div>

    <!-- 场馆列表 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="venueList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="场馆名称" min-width="150">
          <template #default="{ row }">
            <div class="venue-name">
              <span>{{ row.name }}</span>
              <el-tag
                :type="getStatusType(row.status)"
                size="small"
                style="margin-left: 8px"
              >
                {{ getStatusText(row.status) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="city" label="城市" width="100" />
        <el-table-column prop="country" label="国家" width="100" />
        <el-table-column prop="capacity" label="容量" width="100">
          <template #default="{ row }">
            {{ row.capacity ? `${row.capacity}人` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序优先级" width="100">
          <template #default="{ row }">
            <div v-if="row.sortOrder !== undefined" class="sort-priority">
              <el-tag 
                :type="getSortPriorityType(row.sortOrder)"
                size="small"
              >
                {{ row.sortOrder }}
              </el-tag>
              <span class="sort-desc">优先级</span>
            </div>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" width="120" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="info" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 场馆表单对话框 -->
    <VenueForm
      v-model:visible="formVisible"
      :venue-data="currentVenue"
      :is-edit="isEdit"
      @success="handleFormSuccess"
    />

    <!-- 场馆详情对话框 -->
    <VenueDetail
      v-model:visible="detailVisible"
      :venue-id="currentVenueId"
      @edit="handleEditFromDetail"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Delete } from '@element-plus/icons-vue'
import type { VenueData, VenueQuery, VenueStats, VenueListResponse, VenueListData } from '@/api/venue'
import {
  getVenues,
  deleteVenue,
  batchUpdateVenueStatus,
  getVenueStats
} from '@/api/venue'
import VenueForm from './components/VenueForm.vue'
import VenueDetail from './components/VenueDetail.vue'
import { formatDate } from '../../utils/date'

// 响应式数据
const loading = ref(false)
const venueList = ref<VenueData[]>([])
const stats = ref<VenueStats | null>(null)
const selectedIds = ref<number[]>([])
const formVisible = ref(false)
const detailVisible = ref(false)
const currentVenue = ref<VenueData | null>(null)
const currentVenueId = ref<number | null>(null)
const isEdit = ref(false)

// 查询参数
const queryParams = reactive<VenueQuery>({
  page: 1,
  pageSize: 20,
  keyword: '',
  status: '',
  city: '',
  country: '',
  sortBy: 'sortOrder', // 默认排序字段
  sortOrder: 'asc' // 默认排序方向
})

// 分页信息
const pagination = reactive({
  total: 0,
  page: 1,
  pageSize: 20,
  totalPages: 0
})

// 获取场馆列表
const fetchVenues = async () => {
  try {
    loading.value = true
    const response = await getVenues(queryParams)
    console.log(response)
    
    // 处理后端返回的数据结构
    if (response.success && response.data) {
      venueList.value = response.data.data
      Object.assign(pagination, response.data.pagination)
    } else {
      console.error('获取场馆列表失败:', response.message)
      ElMessage.error(response.message || '获取场馆列表失败')
    }
  } catch (error) {
    console.error('获取场馆列表失败:', error)
    ElMessage.error('获取场馆列表失败')
  } finally {
    loading.value = false
  }
}

// 获取统计信息
const fetchStats = async () => {
  try {
    const response = await getVenueStats()
    if (response.success && response.data) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  fetchVenues()
}

// 重置
const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    pageSize: 20,
    keyword: '',
    status: '',
    city: '',
    country: '',
    sortBy: 'sortOrder', // 默认排序字段
    sortOrder: 'asc' // 默认排序方向
  })
  fetchVenues()
}

// 分页处理
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  queryParams.page = 1
  fetchVenues()
}

const handleCurrentChange = (page: number) => {
  queryParams.page = page
  fetchVenues()
}

// 选择处理
const handleSelectionChange = (selection: VenueData[]) => {
  selectedIds.value = selection.map(item => item.id!).filter(Boolean)
}

// 新增场馆
const handleCreate = () => {
  currentVenue.value = null
  isEdit.value = false
  formVisible.value = true
}

// 编辑场馆
const handleEdit = (row: VenueData) => {
  currentVenue.value = { ...row }
  isEdit.value = true
  formVisible.value = true
}

// 从详情页面编辑场馆
const handleEditFromDetail = (venueData: VenueData) => {
  currentVenue.value = { ...venueData }
  isEdit.value = true
  formVisible.value = true
}

// 查看场馆
const handleView = (row: VenueData) => {
  currentVenueId.value = row.id!
  detailVisible.value = true
}

// 删除场馆
const handleDelete = async (row: VenueData) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除场馆"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteVenue(row.id!)
    if (response.success) {
      ElMessage.success('删除成功')
      fetchVenues()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除场馆失败:', error)
      ElMessage.error('删除场馆失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个场馆吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里可以实现批量删除逻辑
    ElMessage.success('批量删除成功')
    selectedIds.value = []
    fetchVenues()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量更新状态
const handleBatchStatus = async (status: string) => {
  try {
    const statusText = getStatusText(status)
    await ElMessageBox.confirm(
      `确定要将选中的 ${selectedIds.value.length} 个场馆状态更新为"${statusText}"吗？`,
      '确认批量更新',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await batchUpdateVenueStatus(selectedIds.value, status)
    if (response.success) {
      ElMessage.success('批量更新状态成功')
      selectedIds.value = []
      fetchVenues()
      fetchStats()
    } else {
      ElMessage.error(response.message || '批量更新状态失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量更新状态失败:', error)
      ElMessage.error('批量更新状态失败')
    }
  }
}

// 表单成功回调
const handleFormSuccess = () => {
  formVisible.value = false
  fetchVenues()
  fetchStats()
}

// 排序处理
const handleSortChange = () => {
  queryParams.page = 1
  fetchVenues()
}

// 状态相关
const getStatusType = (status: string): 'success' | 'info' | 'warning' | 'danger' => {
  const statusMap: Record<string, 'success' | 'info' | 'warning' | 'danger'> = {
    ACTIVE: 'success',
    INACTIVE: 'info',
    MAINTENANCE: 'warning'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: '活跃',
    INACTIVE: '停用',
    MAINTENANCE: '维护中'
  }
  return statusMap[status] || '未知'
}

// 排序优先级相关
const getSortPriorityType = (priority: number): 'success' | 'info' | 'warning' | 'danger' => {
  if (priority === 1) return 'success';
  if (priority === 2) return 'info';
  if (priority === 3) return 'warning';
  return 'info'; // 默认或未知优先级
};

// 初始化
onMounted(() => {
  fetchVenues()
  fetchStats()
})
</script>

<style scoped lang="scss">
.venue-management {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
    }
  }

  .stats-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        text-align: center;
        padding: 20px;

        .stat-number {
          font-size: 32px;
          font-weight: bold;
          margin-bottom: 8px;

          &.active { color: #67c23a; }
          &.inactive { color: #909399; }
          &.maintenance { color: #e6a23c; }
        }

        .stat-label {
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .venue-name {
    display: flex;
    align-items: center;
  }

  .sort-priority {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .sort-desc {
    font-size: 12px;
    color: #909399;
  }

  .text-muted {
    color: #c0c4cc;
    font-size: 12px;
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
